unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, Unit2;

type
  TForm1 = class(TForm)
    btnPath: TButton;
    btnRest: TButton;
    dlg: TOpenDialog;
    btnAbrir: TButton;
    pb: TProgressBar;
    lblStat: TLabel;
    function Compare(p:integer):boolean;
    procedure Path;
    procedure btnAbrirClick(Sender: TObject);
    procedure btnPathClick(Sender: TObject);
    procedure btnRestClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

const
 cfind = 'Ringtones.plist';
 creplace = 'Ringtones-plist';
 leng = 15;
 lengb = 900;

var
  Form1: TForm1;
  fle: string;
  stm: TFileStream;
  vb,vs:array[0..14] of byte;
  buffer:array[0..(lengb-1)] of byte;
  find, replace:string;
  qtd:integer;

implementation

{$R *.dfm}

procedure TForm1.btnRestClick(Sender: TObject);
begin
 find:=creplace;
 replace:=cfind;
 ThrPath.Create(false);
end;

procedure TForm1.btnAbrirClick(Sender: TObject);
begin
 if dlg.Execute then
  begin
   fle:=dlg.FileName;
   if FileExists(fle) then
    begin
     try
      stm:=TFileStream.Create(fle,fmOpenReadWrite OR fmShareExclusive);
      if stm.Size = 0 then 
       begin
        MessageDlg('0 sized file!',mtError,[mbOK],0);
        stm.Free;
        exit;
       end;
      btnPath.Enabled:=True;
      btnRest.Enabled:=True;
     except
      MessageDlg('The file could not be opened.',mtError,[mbOK],0);
     end;
    end
   else
    MessageDlg('The file could not be opened.',mtError,[mbOK],0);
  end;
end;


procedure TForm1.btnPathClick(Sender: TObject);
begin
  find:=cfind;
  replace:=creplace;
  ThrPath.Create(false);
end;

procedure TForm1.Path;
var
i,v,qtdl,p:integer;
begin
lblStat.Caption:='Wait...';
btnPath.Enabled:=false;
btnRest.Enabled:=False;

for v := 0 to leng - 1 do
 begin
  vb[v] := ord(find[v+1]);
  vs[v] := ord(replace[v+1]);
 end;

qtd:=stm.Size;
qtdl:=round((qtd div lengb)*21/20)+1;

pb.Max:= qtdl;
pb.Position:= 0;

for i:=0 to qtdl -1 do
 begin
  stm.Seek(i*lengb - i*leng,soFromBeginning);
  stm.Read(buffer,lengb);

  for p := 0 to lengb -1 do
   begin
    if (p + i*lengb -i*leng) > (qtd - leng +1) then
     break;

    if Compare(p) then
     begin
      stm.Seek(i*lengb -i*leng + p,soFromBeginning);
      stm.WriteBuffer(vs, leng);
     end;
   end;
  pb.Position:=pb.Position+1;
 end;
 stm.Free;
 lblStat.Caption:='End';
end;

function TForm1.Compare(p:integer): boolean;
var
i:integer;
begin
result:=true;
for i:= 0 to leng -1  do
 if buffer[i+p] <> vb[i] then
  begin
   result:=false;
   break;
  end
end;

end.
